/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include "AvatarThread.h"
#include <QDesktopServices>
#ifdef QT5
#include <QStandardPaths>
#endif
#include <KMsgFw111Q>
#include <QEventLoop>
#include <QImage>
#include <QTimer>
#include <QDebug>
#include <QFile>
#include <QDir>

AvatarThread::AvatarThread(QStringList arList, QList<QString> arRAMList, QObject *parent) :
    QThread(parent), arList(arList), arRAMList(arRAMList)
{
}

void AvatarThread::run()
{
    KMsgFw111Q *fwat = new KMsgFw111Q();
    QStringList avatarList = arList;
    avatarList.removeDuplicates();
    foreach(QString avatarInRAM,arRAMList)
    {
        if (avatarList.contains(avatarInRAM))
        {
            avatarList.removeAll(avatarInRAM);
        }
    }
#ifdef QT4
    QString msgPath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.kmsg";
    msgPath = msgPath.replace("\\","/");
    msgPath = msgPath.replace("//","/");
    QDir dir;
    dir.mkpath(msgPath);
#elif defined(QT5)
    QString msgPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.kmsg";
    msgPath = msgPath.replace("\\","/");
    msgPath = msgPath.replace("//","/");
    QDir dir;
    dir.mkpath(msgPath);
#endif
    foreach(const QString& avatarImage, avatarList)
    {
        QString avatarPath = msgPath + "/" + avatarImage + ".km";
        if (!QFile::exists(avatarPath))
        {
            QFile *avatarFile = new QFile();
            avatarFile->setFileName(avatarPath);
            if (avatarFile->open(QFile::ReadWrite))
            {
                qDebug() << "Downloading Avatar" << avatarImage;
                QEventLoop loop;
                QNetworkReply *reply = fwat->downloadAvatar(avatarImage,false);
                reply->setObjectName(avatarImage);
                connect(reply,SIGNAL(finished()),&loop,SLOT(quit()));
                QTimer::singleShot(150000,&loop,SLOT(quit()));
                loop.exec();
                loop.deleteLater();
                if (reply->isFinished())
                {
                    QByteArray avatarArray = "KM";
                    QByteArray avatarUnArray = reply->readAll();
                    avatarArray += QByteArray::fromHex("11");
                    avatarArray += QByteArray::fromHex("FF");
                    QByteArray containChecksum = QString::number(qChecksum(avatarUnArray.data(),avatarUnArray.length())).toUtf8();
                    while (containChecksum.length() != 6)
                    {
                        containChecksum.insert(0,"0");
                    }
                    avatarArray += QByteArray::fromHex(containChecksum);
                    avatarArray += QByteArray::fromHex("FF");
                    avatarArray += qCompress(avatarUnArray,9);
                    avatarFile->write(avatarArray);
                    avatarFile->flush();
                    avatarFile->close();
                    QImage avatarPixmap = QImage::fromData(avatarUnArray);
                    if (!avatarPixmap.isNull())
                    {
                        qDebug() << "Success loading Avatar" << avatarImage;
                        emit avatarInsert(avatarUnArray,avatarImage);
                    }

                }
                else
                {
                    qDebug() << "Error loading Avatar" << avatarImage;
                    avatarFile->close();
                    avatarFile->remove();
                }
            }
            avatarFile->deleteLater();
        }
        else
        {
            QFile *avatarFile = new QFile();
            avatarFile->setFileName(avatarPath);
            if (avatarFile->open(QFile::ReadOnly))
            {
                QByteArray avatarArray = avatarFile->readAll();
                QString avatarFormat = avatarArray.left(2);
                if (avatarFormat == "KM")
                {
                    avatarArray.remove(0,2);
                    QByteArray versionArray = avatarArray.left(1);
                    int version = 0;
                    version = versionArray.toHex().toInt();
                    avatarArray.remove(0,1);
                    if (version >= 11)
                    {
                        avatarArray.remove(0,1);
                        QByteArray checksumArray = avatarArray.left(3);
                        avatarArray.remove(0,4);
                        avatarArray = qUncompress(avatarArray);
                        QByteArray containChecksum = QString::number(qChecksum(avatarArray.data(),avatarArray.length())).toUtf8();
                        while (containChecksum.length() != 6)
                        {
                            containChecksum.insert(0,"0");
                        }
                        if (checksumArray.toHex() == containChecksum)
                        {
                            qDebug() << "Success to validate Avatar" << avatarImage;
                            QImage avatarPixmap = QImage::fromData(avatarArray);
                            avatarFile->close();
                            avatarFile->deleteLater();
                            if (!avatarPixmap.isNull())
                            {
                                qDebug() << "Success loading Avatar" << avatarImage;
                                emit avatarInsert(avatarArray,avatarImage);
                            }
                            else
                            {
                                qDebug() << "Failed to load Avatar" << avatarImage;
                                QFile::remove(avatarPath);
                            }
                        }
                        else
                        {
                            qDebug() << "Failed to validate Avatar" << avatarImage;
                            avatarFile->close();
                            avatarFile->deleteLater();
                            QFile::remove(avatarPath);
                        }
                    }
                    else if (version >= 10)
                    {
                        avatarArray = qUncompress(avatarArray);
                        QImage avatarPixmap = QImage::fromData(avatarArray);
                        avatarFile->close();
                        avatarFile->deleteLater();
                        if (!avatarPixmap.isNull())
                        {
                            qDebug() << "Success loading Avatar" << avatarImage;
                            emit avatarInsert(avatarArray,avatarImage);
                        }
                        else
                        {
                            qDebug() << "Failed to load Avatar" << avatarImage;
                            QFile::remove(avatarPath);
                        }
                    }
                    else
                    {
                        qDebug() << "To old Version Avatar" << avatarImage;
                        avatarFile->close();
                        avatarFile->deleteLater();
                        QFile::remove(avatarPath);
                    }
                }
                else
                {
                    qDebug() << "Not KM Format Avatar" << avatarImage;
                    avatarFile->close();
                    avatarFile->deleteLater();
                    QFile::remove(avatarPath);
                }
            }
        }
    }
}
